<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="companyid">
              <j-search-select-tag v-model="model.companyid" placeholder="请选择公司"
                dict="sys_depart where org_type='1',depart_name,id"></j-search-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="BOM类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bomoftype">
              <j-dict-select-tag type="list" v-model="model.bomoftype" dictCode="bomoftype" placeholder="请选择BOM类型" />
            </a-form-model-item>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="BOM版本" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="version">
              <a-input-number v-model="model.version" placeholder="请输入版本" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="BOM简称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billcode">
              <a-input v-model="model.billcode" placeholder="请输入清单编号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="父项物料" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialid">
              <c-select-material v-model="model.materialid" placeholder="请选择父项物料" :buttons="false" ></c-select-material>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="父项物料单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="uomid">
              <a-input v-model="model.uomid" placeholder="请选择父项物料单位" disabled></a-input>>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="物料型号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="model">
              <a-input v-model="model.model" placeholder="请选择物料型号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="物料规格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="specs">
              <a-input v-model="model.model" placeholder="请选择物料规格" disabled ></a-input>>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="BOM分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bomtype">
              <j-search-select-tag v-model="model.bomtype" placeholder="请选择BOM分类" dict="BOMTYPES" ></j-search-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="BOM用途" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bomyt">
              <j-search-select-tag v-model="model.bomyt" placeholder="请选择BOM用途" dict="BOMYT"></j-search-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="启用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isenable">
              <a-checkbox v-model="model.isenable" placeholder="请选择"></a-checkbox>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remarks">
              <a-input v-model="model.remarks" placeholder="请输入备注" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="物料清单分录" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="scmbillofmaterialitemTable.loading"
          :columns="scmbillofmaterialitemTable.columns"
          :dataSource="scmbillofmaterialitemTable.dataSource"
          :maxHeight="500"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :bordered="true"
          :toolbar="true"
          :alwaysEdit="true"
          @valueChange="handleValueChange"
          @afterPushRow="afterPushRows"
          @edit-actived="handleAfterValueChange"
          >
        </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="联副产品" :key="refKeys[1]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[1]"
          :loading="scmcobillofmaterialTable.loading"
          :columns="scmcobillofmaterialTable.columns"
          :dataSource="scmcobillofmaterialTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          @valueChange="handleValueChange"
          />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import {queryMaterialVoInfosByIds}  from '@/api/erp/commonapi'

  export default {
    name: 'ScmbillofmaterialForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer
    },
    data() {
      return {
        labelCol: {
          xs: { span: 6 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 6 },
          sm: { span: 16 },
        },
        model:{
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        linkprocconfig:[
            { requestData: this.requestProcData,key:'materialid'}
        ],
        validatorRules: {
          materialid: [{ required: true, message: '请选择父项物料' }],
          bomyt:[{required:true,message:"请选择BOM用途"}],
          bomtype:[{required:true,message:'请选择BOM分类'}],
        },
        refKeys: ['scmbillofmaterialitem', 'scmcobillofmaterial', ],
        tableKeys:['scmbillofmaterialitem', 'scmcobillofmaterial', ],
        activeKey: 'scmbillofmaterialitem',
        // 物料清单分录
        scmbillofmaterialitemTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '行号',
              key: 'itemcode',
               type: JVXETypes.input,
              width:"80px",
              placeholder: '请输入${title}',
              defaultValue:'',
              fixed:"left",
            },
            {
              title: '子项物料',
              key: 'materialid',
              type: JVXETypes.materialSelect,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              linkagekey:"childBomId",
              props: {
                materialtype: '2'
              },
              fixed:"left"
            },
            {
              title: '子项物料编号',
              key: 'materialcode',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              fixed:"left"
            },
            {
              title: '子项物料名称',
              key: 'materialname',
               type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title:"供应类型",
              key:'suppletype',
              type:JVXETypes.sel_search,
              width:"120px",
              dictCode:'GYLX',
              placeholder:'请输入${title}',
              defaultValue:'ZZ',
            },
            {
              title:"子项类型",
              key:'mchildtype',
              type:JVXETypes.sel_search,
              dictCode:'ZXLX',
              width:"120px",
              placeholder:'请输入${title}',
              defaultValue:'BZJ',
            },
            {
              title: '子项单位',
              key: 'uomid',
               type: JVXETypes.sel_search,
              width:"200px",
              placeholder: '请输入${title}',
              dictCode: 'scmuom,uomname,id',
              defaultValue:'',
            },
            {
              title:"子项用量类型",
              key:'yltype',
              type:JVXETypes.sel_search,
              dictCode:'YLLX',
              width:"150px",
              placeholder:'请输入${title}',
              defaultValue:'BD',
            },
            {
              title:"用量:分子",
              key:'fzqty',
              type:JVXETypes.inputNumber,
              width:"120px",
              placeholder:'请输入${title}',
              defaultValue:'1',
              statistics: ['sum']
            },
            {
              title:"用量:分母",
              key:'fmqty',
              type:JVXETypes.inputNumber,
              width:"120px",
              placeholder:'请输入${title}',
              defaultValue:'1',
              statistics: ['sum']
            },
            {
              title:"固定损耗量",
              key:'gdshl',
              type:JVXETypes.inputNumber,
              width:"120px",
              placeholder:'请输入${title}',
              defaultValue:'0',
            },
            {
              title:"变动损耗率%",
              key:'bdshl',
              type:JVXETypes.inputNumber,
              width:"150px",
              placeholder:'请输入${title}',
              defaultValue:'0',
            },
            {
              title:"供应组织",
              key:'suppleorgid',
              type:JVXETypes.sel_search,
              dictCode:"sys_depart where org_type='1',depart_name,id ",
              width:"120px",
              placeholder:'请输入${title}',
              defaultValue:'',
            },
            {
              title:"子项BOM",
              key:'childBomId',
              type:JVXETypes.sel_search,
              dictCode:"scmbillofmaterial,billcode,id",
              width:"300px",
              placeholder:'请输入${title}',
              defaultValue:'',
            },
          ]
        },
        // 联副产品
        scmcobillofmaterialTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料',
              key: 'materialid',
               type: JVXETypes.materialSelect,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              props:{
                materialtype:"2"
              }
            },
            {
              title: '物料名称',
              key: 'materialname',
               type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料编号',
              key: 'materialcode',
               type: JVXETypes.input,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '计量单位',
              key: 'uomid',
               type: JVXETypes.sel_search,
               dictCode:'scmuom,uomname,id',
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '规格',
              key: 'model',
              type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '型号',
              key: 'specs',
              type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '数量',
              key: 'qty',
              type: JVXETypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'1',
            },
            {
              title: '工序',
              key: 'processid',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: 'parentid',
              key: 'parentid',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          add: "/base/scmbillofmaterial/add",
          edit: "/base/scmbillofmaterial/edit",
          queryById: "/base/scmbillofmaterial/queryById",
          scmbillofmaterialitem: {
            list: '/base/scmbillofmaterial/queryScmbillofmaterialitemByMainId'
          },
          scmcobillofmaterial: {
            list: '/base/scmbillofmaterial/queryScmcobillofmaterialByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    watch:{
      "model.materialid":{
          async handler(val,oldval){
            if(val !== oldval){
              let res = await queryMaterialVoInfosByIds({ids:val});
                if(res.success){
                  let resu=res.result;
                  if(resu.length > 0){
                    this.model.uomid = resu[0].stockuomid_dictText
                    this.model.model = resu[0].model
                    this.model.specs = resu[0].mspecs
                  }
                }
            }
          }
      }
    },
    created () {
    },
    methods: {
      async afterPushRows(rows, target) {
      let xtable = rows.$target
      let fullData = xtable.getTableData()
      if (fullData && fullData.length > 0) {
        var j = 10
        for (let i = 0; i < fullData.length; i++) {
          fullData[i].itemcode = j
          j = j + 10
        }
        xtable.tableData = fullData
        await xtable.updateCache(true)
        await xtable.updateData()
        xtable.loadData(fullData);
      }
    },
      addBefore(){
        this.scmbillofmaterialitemTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.scmbillofmaterialitem.list, params, this.scmbillofmaterialitemTable)
          this.requestSubTableData(this.url.scmcobillofmaterial.list, params, this.scmcobillofmaterialTable)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          scmbillofmaterialitemList: allValues.tablesValue[0].tableData,
          scmcobillofmaterialList: allValues.tablesValue[1].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },

    }
  }
</script>

<style scoped>
</style>